package com.ch.ebusiness.controller.before;

import com.ch.ebusiness.entity.BUser;
import com.ch.ebusiness.service.before.UserService;
import com.ch.ebusiness.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 发送短信验证码
     *
     * @param phoneNumber
     * @return
     */
    
    @ResponseBody
    @RequestMapping("/send/message")
    public ResultEntity<String> sendShortMessage(@RequestParam("phoneNumber") String phoneNumber) {
        
        System.out.println(phoneNumber);
        String resultEntity = userService.sendShortMessage(phoneNumber);
        if ("ok".equals(resultEntity)) {
            return ResultEntity.successWithoutData();
        } else {
            return ResultEntity.failed(resultEntity);
        }
        
    }
    
    
    @RequestMapping("/toRegister")
    public String toRegister(@ModelAttribute("bUser") BUser bUser) {
        return "user/register";
    }
    
    @RequestMapping("/toLogin")
    public String toLogin(@ModelAttribute("bUser") BUser bUser) {
        //@ModelAttribute("bUser")与th:object="${bUser}"相对应
        return "user/login";
    }
    
    @RequestMapping("/userLogin")
    public String login(@ModelAttribute("bUser") @Validated BUser bUser,
                        BindingResult rs, HttpSession session, Model model) {
        //if (rs.hasErrors()) {//验证失败
        //    return "user/login";
        //}
        return userService.login(bUser, session, model);
    }
    
    @RequestMapping("/ok")
    public String ok(HttpSession session, BUser bUser) {
        bUser.setPhoneNumber("13033268820");
        bUser.setBemail("2386716789@qq.com");
        bUser.setBpwd("$10$aODwG2cJf5W1JXKINcYrcONDIiUpcMrONe6lwHp8BBh.zQo6vdLqe");
        session.setAttribute("bUser", bUser);
        return "redirect:/";
    }
    
    
    @RequestMapping("/isUse")
    @ResponseBody
    public String isUse(@RequestBody BUser bUser) {
        return userService.isUse(bUser);
    }
    
    @RequestMapping("/register")
    public String register(@ModelAttribute("bUser") @Validated BUser bUser, BindingResult rs) {
        
        return userService.register(bUser);
    }
}
